package com.card.manager.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.framework.page.model.PageModel;
import com.card.framework.util.CommonUtil;
import com.card.manager.domain.Aca;
import com.card.manager.domain.Acb;
import com.card.manager.services.AcaService;
import com.card.manager.services.AcbService;

@Controller
@RequestMapping("/aca")
public class AcaController {
	@Autowired(required=true) 
	private AcaService acaServices;
	@InitBinder
	public void setupDataBinder(WebDataBinder dataBinder) {
		//表单页面如果有时间类型的需要initbinder
		dataBinder.registerCustomEditor(String.class,new StringTrimmerEditor(false));  
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
	/**
	 * 跳转到管理首页
	 */
	@RequestMapping("/index")
	public String aca(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		return "acaList";
	}
	/**
	 * ajax异步查询aca列表,返回jsondata
	 */
	@RequestMapping(value="/queryList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryList(HttpServletRequest request,PageModel pageModel) throws Exception{
		Map<String,String> params = new HashMap<String,String>();
		@SuppressWarnings("unchecked")
		Enumeration<String> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String k = en.nextElement();
			if(k.startsWith("q@")){
				params.put(k.substring(2), request.getParameter(k));
			}
		}
		return acaServices.selectAcaForPage(params, pageModel);
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/exportQueryList",method=RequestMethod.POST)
	public void exportQueryList(HttpServletRequest request,HttpServletResponse response,PageModel pageModel) throws IOException{
		Map<String,String> params = new HashMap<String,String>();
		//组合过滤条件.
		Enumeration<String> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String k = en.nextElement();
			if(k.startsWith("q@")){
				params.put(k.substring(2), request.getParameter(k));
			}
		}
		pageModel.setRows(0);
		//查询结果集.
		Map<String, Object> map = acaServices.selectAcaForPage(params, pageModel);
		String[] titles = {"姓名 ","卡号","消费流水号","POS机编号","商户名称(简)","帐户种类"};
		int[] columnWidth = {3000,2500,2500,2500,5000,2000};
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("充值明细列表");
		//设置横向排版
		sheet.getPrintSetup().setLandscape(true);
		//设置A4纸
		sheet.getPrintSetup().setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);
//		sheet.setDefaultColumnWidth(15);
		sheet.autoSizeColumn(0);
		HSSFCellStyle headerStyle = wb.createCellStyle(); 
		headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 指定单元格居中对齐 
		headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 指定单元格垂直居中对齐 
		Font font = wb.createFont();
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		headerStyle.setFont(font);
		int rowIndex = 0;
		//添加标题
		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titles.length - 1));
		HSSFRow caption = sheet.createRow(rowIndex);
		caption.createCell(0,HSSFCell.CELL_TYPE_STRING).setCellValue("充值明细列表");
		HSSFCellStyle captionStyle = wb.createCellStyle(); 
		captionStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中    
		HSSFFont captionFont = wb.createFont();    
		captionFont.setFontName("黑体");    
		captionFont.setFontHeightInPoints((short) 16);
		captionStyle.setFont(captionFont);
		caption.getCell(0).setCellStyle(captionStyle);
		caption.setHeight((short)500);
		rowIndex++;
		//添加表头
		HSSFRow title = sheet.createRow(rowIndex);
		rowIndex++;
		for(int i = 0;i < titles.length;i++){
			title.createCell(i,HSSFCell.CELL_TYPE_STRING).setCellValue(titles[i]);
			title.getCell(i).setCellStyle(headerStyle);
			sheet.setColumnWidth(i, columnWidth[i]);
		}
		HSSFCellStyle bodyStyle = wb.createCellStyle(); 
		bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		bodyStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		//添加数据
		HSSFRow rowData = null;
		
		List<Aca> itemList = (List<Aca>)map.get("rows");
		for(Aca aca : itemList){
			if(aca == null)
				continue;
			rowData = sheet.createRow(rowIndex);
			//添加充值日期
			rowData.createCell(0, HSSFCell.CELL_TYPE_STRING)
				.setCellValue(aca.getAba().getAaa().getUsername());
			//添加卡号
			rowData.createCell(1, HSSFCell.CELL_TYPE_STRING)
				.setCellValue(aca.getAbaid());
			rowData.createCell(2, HSSFCell.CELL_TYPE_STRING).setCellValue(aca.getId());
			//添加充值类型
			rowData.createCell(3, HSSFCell.CELL_TYPE_STRING)
				.setCellValue(aca.getAacid());
			rowData.createCell(4, HSSFCell.CELL_TYPE_STRING).setCellValue(aca.getAab().getNamesimp());
			//添加余额
			rowData.createCell(5, HSSFCell.CELL_TYPE_STRING).setCellValue(aca.getMoneytype());
			rowIndex++;
		}
		wb.setPrintArea(0, 0, titles.length-1, 0, rowIndex);
		
		response.setContentType("application/vnd.ms-excel");
		Date date = new Date();
		
		String headerDisp = "attachment;filename=退货_" + DateFormatUtils.format(date,"yyyyMMddHHmmss") + ".xls";
		headerDisp = new String(headerDisp.getBytes("gbk"), "iso8859-1");
		response.setHeader("content-disposition", headerDisp);
		wb.write(response.getOutputStream());
	}
	/**
	 * 跳转到退货页面<br>
	 */
	@RequestMapping("/acaReturnPopWindow")
	public String add(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("acaid");
		Aca aca = null;
		if(StringUtils.isNotEmpty(id)){
			aca = acaServices.getById(id);
		}
		request.setAttribute("aca", aca);
		return "acaReturnPopWindow";
	}
	
	@RequestMapping(value="/acaReturnPopWindowAcaReturn",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> addOrUpdate(HttpServletRequest request) throws Exception{
		String acaid = request.getParameter("acaid");
		String returnReason = request.getParameter("returnReason");
		String returnMoney = request.getParameter("returnMoney");
		SecurityContext sc = (SecurityContext)request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
		Map<String, String> map = new HashMap<String, String>();
		try {
			acaServices.returnAac(acaid, returnReason, new BigDecimal(returnMoney), sc.getAuthentication().getName());
			map.put("mes", "操作成功");
		}
		catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map; 
	}
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, String> delete(@RequestParam("json") String json){
		Map<String, String> map = new HashMap<String, String>();
		try {
			acaServices.deleteAcas(CommonUtil.getBean(json, Aca.class));
			map.put("mes", "删除成功");
		} catch (Throwable e) {
			CommonUtil.throwsException(map, e);
		}
		return map;//重定向
	}@RequestMapping("/acaSum")
	public String acaSum(HttpServletRequest request,HttpSession session,
			HttpServletResponse response) throws IOException {
		return "acaSumList";
	}
	/**
	 * ajax异步查询aca列表,返回jsondata
	 */
	@RequestMapping(value="/queryAcaSumList",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> queryAcaSumList(HttpServletRequest request,PageModel pageModel) throws Exception{
		Map<String,String> params = new HashMap<String,String>();
		@SuppressWarnings("unchecked")
		Enumeration<String> en = request.getParameterNames();
		while(en.hasMoreElements()){
			String k = en.nextElement();
			if(k.startsWith("q@")){
				params.put(k.substring(2), request.getParameter(k));
			}
		}
		return acaServices.selectAcaSumForPage(params, pageModel);
	}
}
